#include "CGIVulkanMemory.h"
#include "CGIVulkanDevice.h"
namespace Alice{
    VulkanFence::VulkanFence(CGIVulkanDevice*inDevice,FenceManager*inOwner,bool inbCreateSignaled)
        :mFenceManager(inOwner)
        ,mState(inbCreateSignaled?EState::Signaled:EState::NotReady)
    {
        VkFenceCreateInfo Info={};
        Info.sType=VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
        Info.flags = inbCreateSignaled ? VK_FENCE_CREATE_SIGNALED_BIT : 0;
        vkCreateFence(inDevice->GetDevice(), &Info, NULL, &mFence);
    }
    VulkanFence::~VulkanFence()
    {
        
    }
    VulkanSemaphore::VulkanSemaphore(CGIVulkanDevice& inDevice):mDevice(inDevice)
    {
        VkSemaphoreCreateInfo CreateInfo={};
        CreateInfo.sType=VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
        vkCreateSemaphore(mDevice.GetDevice(), &CreateInfo, NULL, &mSemaphore);
    }
    FenceManager::FenceManager()
        :mDevice(nullptr)
    {
        
    }
    void FenceManager::Init(CGIVulkanDevice* inDevice)
    {
        mDevice=inDevice;
    }

    VulkanFence* FenceManager::AllocateFence(bool bCreateSignaled)
    {
        /*if (FreeFences.Num() != 0)
        {
            FFence* Fence = FreeFences[0];
            FreeFences.RemoveAtSwap(0, EAllowShrinking::No);
            UsedFences.Add(Fence);

            if (bCreateSignaled)
            {
                Fence->State = FFence::EState::Signaled;
            }
            return Fence;
        }*/

        VulkanFence* NewFence = new VulkanFence(mDevice, this, bCreateSignaled);
        //UsedFences.Add(NewFence);
        return NewFence;
    }
    bool FenceManager::WaitForFence(VulkanFence* Fence, uint64 TimeInNanoseconds)
    {
        VkResult Result = vkWaitForFences(mDevice->GetDevice(), 1, &Fence->mFence, true, TimeInNanoseconds);
        switch (Result)
        {
        case VK_SUCCESS:
            Fence->mState = VulkanFence::EState::Signaled;
            return true;
        case VK_TIMEOUT:
            break;
        default:
            break;
        }

        return false;
    }
}